﻿using System;
using System.IO;
using System.Threading;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Interactivity;
using Blacklight.Controls;

namespace SilverlightWebcamEncoder.Behaviors
{
    public class MediaPlayerPathToStreamBehavior : Behavior<MediaPlayer>
    {
        public string Source
        {
            get { return (string)GetValue(SourceProperty); }
            set { SetValue(SourceProperty, value); }
        }

        public static readonly DependencyProperty SourceProperty =
            DependencyProperty.Register("Source", typeof(string), typeof(MediaPlayerPathToStreamBehavior), new PropertyMetadata("", OnSourceChangedStatic));

        
        private static void OnSourceChangedStatic(DependencyObject sender, DependencyPropertyChangedEventArgs e)
        {
            (sender as MediaPlayerPathToStreamBehavior).OnSourceChanged(e);
        }

        private Stream m_lastMediaStream;

        private void OnSourceChanged(DependencyPropertyChangedEventArgs e)
        {
            if (AssociatedObject == null)
                return;

            if (string.IsNullOrEmpty(Source))
            {
                AssociatedObject.Stop();

                AssociatedObject.SetSource(new MemoryStream());

                if (m_lastMediaStream != null)
                    m_lastMediaStream.Close();

                m_lastMediaStream = null;
                
                return;
            }

            try
            {
                m_lastMediaStream = File.Open(Source, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);

                AssociatedObject.SetSource(m_lastMediaStream);
            }
            catch (Exception)
            {
                throw;
            }
        }

        protected override void OnAttached()
        {
            base.OnAttached();
        }
    }
}
